<template>
  <div class="CandidateApplication">
    <div class="titleTop first">
      <h3>{{$t('navigation.review_resume')}}{{data.name? `“${data.name}”`:""}}</h3>
      <a href="javascript:;" @click="closeEmail(true)" v-if="deliveryId && twoArrCludes(['NORMAL', 'COMPANY_MANAGER'])">{{$t('candidateApplication.send_rsume_email')}}</a>
      <span class="back" v-if="id || deliveryId" @click="back"><i class="iconfont icon-zuojiantou"></i>{{$t('common.back')}}</span>
    </div>
    <div class="content">
      <a-result :title="$t('candidateApplication.choiseInList')" v-if="!this.id && !deliveryId">
      </a-result>
      <template v-else>
        <a-card class="formData">
          <a-tabs default-active-key="1" @change="callback">
            <a-tab-pane key="1" :tab="$t('candidateApplication.normal_resume')">
              <div v-if="loadingResume" style="text-align:center">
                <a-spin/>
              </div>
              <resume-standard v-else :enterpriseId="enterpriseId" :positionId="positionId" :resumeTemplates="resumeTemplates" :resumeData="resumeData" :id="id"/>
            </a-tab-pane>
            <a-tab-pane key="2" :tab="$t('candidateApplication.original_resume')" force-render v-if="orcView && orcView.length > 0">
              <!-- <embed :src="resumeAttachments[0].url"></embed> -->
              <a-select style="width:320px;" v-model="selectAttachId" @change="changeResume">
                <a-select-option v-for="item in orcView" :key="item._id || item.attachmentId" :value="item._id || item.attachmentId" :fileType="item.fileType">
                  {{item.name}}
                </a-select-option>
              </a-select>
              <div>
                <iframe ref="iframeResume" v-if="orcView" :src="`${this.resumeData.resumeURL}?attachmentId=${selectAttachId}&fileType=${fileType}`" class="iframe" ></iframe>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <div v-if="id || deliveryId">
          <a-card :title="$t('candidateApplication.cadidata_navs')" class="resumeCard" size="small">
            <a-pagination simple :current="current" :pageSize="1" :total="max" @change="pageChange"/>
          </a-card>
          <a-card :title="$t('candidateApplication.apply_position_info')" class="resumeCard" size="small" v-if="deliveryId">
            <h4>{{positionInfo.positionName}}</h4>
            <p>{{positionInfo.positionPlace}}</p>
            <p>{{$t('candidateApplication.dateCreated')}}：{{positionInfo.dateCreated}}</p>
            <p v-if="positionInfo.lastOper">{{$t('candidateApplication.already_config')}}{{positionInfo.lastOper}}：{{positionInfo.opratorDate}}</p><!-- 记录最后一次 -->
            <p class="btn" v-if="twoArrCludes(['NORMAL', 'COMPANY_MANAGER'])">
              <a-button class="green" v-if="positionInfo.operatorStatus !== 'Accepted'" @click="batchOperation('Accepted')">{{$t('candidateApplication.accepted')}}</a-button>
              <a-button type="danger" v-if="positionInfo.operatorStatus !== 'Rejected'" @click="batchOperation('Rejected')">{{$t('candidateApplication.rejected')}}</a-button>
              <a-button type="primary" v-if="positionInfo.pending === false" @click="batchOperation('pending')">{{$t('candidateApplication.pending')}}</a-button> <!-- 需要处理待定或者非待定状态 合适和不合适-->
              <a-button type="primary" v-if="positionInfo.pending === true" @click="batchOperation('cancelPending')">{{$t('candidateApplication.cancel_pending')}}</a-button>
              <a-button class="grey" v-if="positionInfo.placeFile === false" @click="batchOperation('placeOnFile')">{{$t('candidateApplication.placeFile')}}</a-button>
            </p>
          </a-card>
          <a-card :title="$t('candidateApplication.active_info')" class="resumeCard" size="small">
            <p>{{$t('candidateApplication.resume_create')}}：{{data.dateCreated && moment(data.dateCreated).format('YYYY年M月DD日')}}</p>
            <p>{{$t('candidateApplication.last_updated')}}：{{data.lastUpdated && moment(data.lastUpdated).format('YYYY年M月DD日')}}</p>
            <p>{{$t('candidateApplication.delivery_count')}}：<span class="under blue" @click="searchResume">{{data.deliveryCount}}</span></p>
            <p>{{$t('candidateApplication.last_logined')}}：{{data.lastLogined && moment(data.lastLogined).format('YYYY年M月DD日')}}</p>
            <p>{{$t('candidateApplication.login_acct')}}：{{data.email || data.mobile}}</p>
            <template slot="actions" v-if="twoArrCludes(['SITE_MANAGER'])">
              <span>
                <a-popconfirm
                  :title="`${$t('candidateApplication.confirm_delete_acct')}?`"
                  @confirm="deleteAcct"
                  :okText="$t('common.confirm')"
                  :cancelText="$t('common.cancel')"
                >
                  <a href="javascript:;" class="red under">{{$t('common.delete')}}</a>
                </a-popconfirm>
              </span>
              <span class="blue under" @click="updateActivation">{{data.status? $t('common.disable') : $t('common.enable')}}</span>
            </template>
          </a-card>
          <a-card :title="$t('candidateApplication.original_resume_file')" class="resumeCard" size="small" :loading="loading3"  v-if="resumeAttachments && resumeAttachments.length > 0">
            <ul>
              <li v-for="item in resumeAttachments" :key="item.attachmentId">
                <a-tooltip>
                  <template slot="title">
                    {{item.name}}
                  </template>
                  <a class="blue" :href="item.url">{{item.name}}</a>
                </a-tooltip>
              </li>
            </ul>
          </a-card>
          <a-card :title="$t('candidateApplication.resume_file')" class="resumeCard" size="small" :loading="loading3">
            <a-upload-dragger
              :showUploadList="false"
              name="file"
              :multiple="true"
              :headers="{Authorization}"
              :data="{id: deliveryId, resumeId: resumeData.id}"
              :beforeUpload="beforeUpload"
              action="/jobboard/jobboardcandidates/candidate/uploadFile"
              @change="handleChange">
              <p class="ant-upload-drag-icon">
                <a-icon type="upload" />
              </p>
              <p class="ant-upload-text">
                {{$t('candidateApplication.drag_file_here')}} <br/>
              <span class="types">{{$t('candidateApplication.file_type')}} "DOC", "doc", "DOCX", "docx", "HTML", "html", "PDF", "pdf", "TXT", "txt", "mht", "jpg", "bmp", "png" </span>
              </p>
            </a-upload-dragger>
            <ul v-if="otherAttachments && otherAttachments.length > 0">
              <li>
                <span>{{$t('candidateApplication.file_name')}}</span>
                <span>{{$t('candidateApplication.operate')}}</span>
              </li>
              <li v-for="item in otherAttachments" :key="item.attachmentId">
                 <a-tooltip>
                  <template slot="title">
                    {{item.name}}
                  </template>
                  <a :href="item.url" target="_blank">{{item.name}}</a>
                </a-tooltip>
                <span class="red" @click="deleteAtta(item.attachmentId)"><a-icon type="delete" /></span>
              </li>
            </ul>
          </a-card>
        </div>
      </template>
    </div>
    <sendEmail :visible="email" @close="closeEmail" :deliveryId="deliveryId" :resumeAttachments="[...resumeAttachments, ...otherAttachments]"></sendEmail>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
import { resumeData, findPositionByApplication, applicationOperator, candidateResume, resumeTemplate, candidatefindAttachments, candidatedeleteAttachment } from '@/api/resume'
import ResumeStandard from '@/components/resume/ResumeStandard'
import sendEmail from '@/components/resume/sendEmail'
import { changeAccountStatus, deleteAccount } from '@/api/config'
import { twoArrCludes } from '@/util/roles'
export default {
  name: 'CandidateApplication',
  components: { sendEmail, ResumeStandard },
  data () {
    return {
      resumeTemplates: [],
      loading3: false,
      resumeAttachments: [],
      otherAttachments: [],
      max: 0,
      current: 1,
      listId: [],
      email: false,
      fileType: '',
      positionId: '',
      enterpriseId: '',
      resumeData: {},
      orcView: [],
      selectAttachId: '',
      loadingResume: false,
      deliveryId: '',
      id: '',
      deliveryList: [],
      data: {},
      positionInfo: {}
    }
  },
  created () {
    this.deliveryId = this.$route.query.deliveryId
    this.id = this.$route.query.id
    this.initDta()
  },
  computed: {
    ...mapState({
      Authorization: function (state) {
        let token = state.common.loginInfo && state.common.loginInfo.token
        return token
      }
    })
  },
  mounted () {
    // if (this.id || this.deliveryId) {
    //   this.$refs.iframeResume.onload = () => {
    //     setTimeout(this.setIframeHeight, 300)
    //     // this.setIframeHeight(this.$refs.iframeResume)
    //   }
    // }
  },
  watch: {
    $route: {
      handler (val, oldVal) {
        if (val.query.id && val.query.id !== oldVal.query.id) {
          this.id = val.query.id
          this.getTemplate()
          this.getResumeData()
        }
        if (val.query.deliveryId && val.query.deliveryId !== oldVal.query.deliveryId) {
          this.deliveryId = val.query.deliveryId
          this.getTemplate()
          this.getResumeData()
          this.findPosition()
        }
      },
      deep: true
    }
  },
  methods: {
    moment,
    twoArrCludes,
    beforeUpload (file) {
      // "DOC", "doc", "DOCX", "docx", "HTML", "html", "PDF", "pdf", "TXT", "txt", "mht", "jpg", "bmp", "png"
      const reg = /\.(DOC|doc|DOCX|docx|HTML|html|PDF|pdf|TXT|txt|mht|jpg|bmp|png)(\?.*)?$/
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          const isLt20M = file.size / 1024 / 1024 < 20
          if (!isLt20M) {
            this.$message.error(this.$t('candidateApplication.file_size_20m'))
            return false
          }
          // this.fileList = [...this.fileList, file]
          resolve(file)
        } else {
          this.$message.error(`${this.$t('candidateApplication.correct_file_type')}`)
          reject(new Error(`${this.$t('candidateApplication.correct_file_type')}`))
        }
      })
    },
    handleChange (e) {
      if (e.file.status === 'done') {
        this.findAtta()
        this.$message.success('附件上传成功！')
      } else if (status === 'error') {
        this.$message.error(e.file.response.message)
      } else if (status === 'removed') {
      }
    },
    async deleteAtta (attachmentId) { // 删除单个建立附件
      this.loading3 = true
      let res = await candidatedeleteAttachment({ resumeId: this.resumeData.id, attachmentId })
      if (res.code === 200) {
        this.findAtta()
      } else {
        this.loading3 = false
        this.$message.error(res.message)
      }
    },
    async findAtta () { // 获取简历附件
      this.loading3 = true
      let res = await candidatefindAttachments({ userId: this.id, id: this.deliveryId })
      if (res.code === 200) {
        this.otherAttachments = res.otherAttachments || []
        this.resumeAttachments = res.resumeAttachments || []
      } else {
        this.$message.error(res.message)
      }
      this.loading3 = false
    },
    async getTemplate () {
      let res = await resumeTemplate({ userId: this.id, deliveryId: this.deliveryId })
      if (res.code === 200) {
        // 处理表单数据并传递给页面
        this.resumeTemplates = res.data.fields
        this.getResume()
      } else {
        this.$message.error(res.message)
      }
    },
    async getResume () { // 获取简历标准数据 deliveryId? `deliveryId=${deliveryId}`:`userId=${id}`
      // this.loadingResume = true
      // let res = await candidateResume({ userId: this.id, deliveryId: this.deliveryId })
      // if (res.code === 200) {
      //   // 处理表单数据并传递给页面
      //   this.resumeData = res.data
      //   // c处理附件 简历原文
      //   this.orcView = res.data.extensionFields && res.data.extensionFields.resumeAttachments && res.data.extensionFields.resumeAttachments.map(item => {
      //     item.fileType = item.name && item.name.split('.').slice(-1)[0]
      //     return item
      //   })
      //   if (this.orcView && this.orcView[0]) {
      //     this.selectAttachId = this.orcView[0]._id || this.orcView[0].attachmentId
      //     this.fileType = this.orcView[0].fileType
      //   }
      //   this.findAtta()
      // } else {
      //   this.$message.error(res.message)
      // }
      // this.loadingResume = false
    },
    changeResume (key, e) {
      this.fileType = e.data.attrs.fileType
    },
    callback (e) {
      this.activeKey = e
      if (e === '2') {
        this.$nextTick(() => {
          setTimeout(this.setIframeHeight, 300)
        })
      }
    },
    closeEmail (flag) {
      this.email = flag
    },
    setStatus (status, value) {
      this.positionInfo[status] = value
    },
    async batchOperation (operator) {
      let deliveryId = this.deliveryId
      let params = {
        ids: deliveryId,
        operator
      }
      let res = await applicationOperator(params)
      if (res.code === 200) {
        switch (operator) {
          case 'Accepted':
            this.setStatus('operatorStatus', operator)
            break
          case 'Rejected':
            this.setStatus('operatorStatus', operator)
            break
          case 'placeOnFile':
            this.setStatus('placeOnFile', true)
            break
          case 'pending':
            this.setStatus('pending', true)
            break
          case 'cancelPending':
            this.setStatus('pending', false)
            break
        }
        // 成功后刷新界面
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    setIframeHeight () {
      let iframe = this.$refs.iframeResume
      if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
        if (iframeWin.document.body) {
          iframe.height = iframeWin.document.documentElement.offsetHeight || iframeWin.document.body.offsetHeight
        }
      }
    },
    back () {
      let path = '/registeredAccount/registeredAccountList'
      if (this.deliveryId) {
        path = `/resume/candidateApplication`
      }
      this.$router.push(path)
    },
    searchResume () {
      this.$router.push(`/resume/candidateApplication?candidateUserId=${this.id}`)
    },
    async deleteAcct () {
      let prams = {
        userId: this.id
      }
      let res = await deleteAccount(prams)
      if (res.code === 200) {
        let path = '/registeredAccount/registeredAccountList'
        if (this.deliveryId) {
          path = `/resume/candidateApplication`
        }
        this.$router.push(path)
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    async updateActivation () {
      let prams = {
        status: !this.data.status + '',
        userId: this.id
      }
      let res = await changeAccountStatus(prams)
      if (res.code === 200) {
        this.$message.success(res.message)
        this.getResumeData()
      } else {
        this.$message.error(res.message)
      }
    },
    pageChange (current, pageSize) { // listId
      this.current = current
      let params = {
        id: this.listId[current - 1]
      }
      if (this.deliveryList && this.deliveryList.length) {
        params.deliveryId = this.deliveryList[current - 1]
      }
      this.$router.push({ query: params })
    },
    initDta () {
      if (!this.id && !this.deliveryId) {
        return
      }
      let resumeList = JSON.parse(sessionStorage.getItem('resumeList'))
      if (resumeList) {
        this.listId = resumeList.list.map(item => item ? item.toString() : '')
        this.deliveryList = resumeList.deliveryList && resumeList.deliveryList.map(item => item ? item.toString() : '')
        this.max = this.listId.length
        this.current = this.deliveryList ? this.deliveryList.indexOf(this.deliveryId) + 1 : this.listId.indexOf(this.id) + 1
        // this.path = resumeList.path
      } else {
        this.max = 1
      }
      this.getTemplate()
      this.getResumeData()
      if (this.deliveryId) {
        this.findPosition()
      }
    },
    async  findPosition () {
      // this.loading = true
      // let params = {
      //   id: this.deliveryId
      // }
      // let res = await findPositionByApplication(params)
      // if (res.code === 200) {
      //   this.positionInfo = res.data
      // } else {
      //   this.$message.error(res.message)
      // }
      // this.loading = false
    },
    async getResumeData () {
      this.loading = true
      let params = {
        id: this.id
      }
      let res = await resumeData(params)
      if (res.code === 200) {
        this.data = res.data
      } else {
        this.$message.error(res.message)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.CandidateApplication
  .iframe
    margin-top 12px
    width 100%
    min-height 795px
  .formData
    flex 1
    margin-right 24px
  .ant-result
    flex 1
    background #fff
  .ant-pagination
    text-align center
  .titleTop
    background #fff
    display flex
    align-items center
    justify-content flex-start
    padding  0 24px 12px
    h3
      margin-right 24px
      font-size 18px
      font-weight bold
    .back
      margin-left auto
      margin-right 7px
      cursor pointer
      color var(--blue-500)
  .content
    padding 12px 24px
    display flex
    justify-content space-between
    iframe
      flex 1
      margin-right 24px
    .resumeCard
      width 380px
      margin-top 12px
      &:first-child
        margin 0
      h4
        font-weight bold
      p
        margin 0
        line-height 28px
      .btn
        margin-top 10px
        display flex
        justify-content space-between
        .green
          background lightGreen
          color #fff
          border none
      .grey
        background textDisable
        color #fff
      .red
        color errorColor
      .blue
        color var(--blue-500)
      .under
        cursor pointer
        text-decoration underline
      ul
          margin-top 12px
          li
            border-top 1px solid borderColor
            line-height 32px
            display flex
            justify-content space-between
            padding 0 12px
            a
              text-overflow ellipsis
              overflow hidden
              white-space nowrap
              word-break break-all
            .red
              margin-left 6px
            &:last-child
              border-bottom 1px solid borderColor
</style>
